package com.scholarship.system.config.security;

import com.scholarship.system.common.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    @Lazy
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        final String requestURI = request.getRequestURI();

        // 如果是登录相关接口，不进行JWT验证
        if (requestURI.startsWith("/api/auth/login")) {
            log.debug("登录接口不进行JWT验证: {}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        try {
            log.debug("请求URI: {}, 方法: {}", requestURI, request.getMethod());
            String jwt = getJwtFromRequest(request);

            if (StringUtils.hasText(jwt)) {
                try {
                    // 尝试获取用户名，这里不进行完整验证
                    String username = jwtUtil.extractUsername(jwt);
                    log.debug("从JWT中提取的用户名: {}", username);

                    // 如果安全上下文中还没有认证信息，则尝试加载用户并设置认证信息
                    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                        try {
                            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                            log.debug("成功加载用户: {}, 权限: {}", userDetails.getUsername(), userDetails.getAuthorities());

                            if (jwtUtil.validateToken(jwt, userDetails)) {
                                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                        userDetails, null, userDetails.getAuthorities());
                                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                                SecurityContextHolder.getContext().setAuthentication(authentication);
                                log.debug("设置认证信息到Security上下文, 用户: {}", username);
                            } else {
                                log.warn("JWT无效，用户: {}", username);
                            }
                        } catch (UsernameNotFoundException e) {
                            log.warn("找不到对应用户: {}", username, e);
                        }
                    }
                } catch (Exception e) {
                    log.error("JWT处理过程中发生异常", e);
                }
            } else {
                log.debug("请求中未找到JWT: {}", requestURI);
            }
        } catch (Exception e) {
            log.error("JWT过滤器发生异常", e);
        }

        filterChain.doFilter(request, response);
    }

    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        log.debug("Authorization头: {}", bearerToken);

        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}